from app import db
from flask import jsonify
from ..domain.user import User


def get_user_by_roomId(roomId):
    uList = User.query.filter(User.roomid == roomId)
    return uList


def get_user_by_username(username):
    user = User.query.get(username)
    return user


def get_user_by_username_and_password(username, password):
    user = User.query.filter(User.username == username, User.password == password)
    return user


def add_user(username, password, roomId):
    try:
        new_user = User(username=username, password=password, roomid=roomId)
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()


def update_user(username, password, telephone, roomId):
    try:
        user = User.query.filter(User.username == username).first()
        user.password = password
        user.telephone = telephone
        user.roomid = roomId
        db.session.commit()
        return "success"

    except Exception as e:
        print(e)
        db.session.rollback()
        return "fail"


def get_user_by_phoneNumber(phoneNumber):
    try:
        user = User.query.filter(User.telephone == phoneNumber).first()
        return user
    except Exception as e:
        print(e)
        db.session.rollback()
        return "fail"
